package com.lindroy.androidplayer.ui.coin

import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.navigation.fragment.findNavController
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseListFragment
import com.lindroy.androidplayer.databinding.FragmentMyCoinsBinding
import com.lindroy.androidplayer.ui.adapter.CoinHistoryAdapter
import com.lindroy.androidplayer.utils.addSimpleDivider
import com.lindroy.androidplayer.utils.collectListWhenResumed
import com.lindroy.androidplayer.viewmodels.MyCoinViewModel

/**
 * @author Lin
 * @date 2022/2/11
 * @function
 */
class MyCoinsFragment : BaseListFragment<FragmentMyCoinsBinding, MyCoinViewModel>() {

    private val adapter by lazy { CoinHistoryAdapter(viewLifecycleOwner) }

    override fun FragmentMyCoinsBinding.initView(savedInstanceState: Bundle?) {
        vm = mViewMode
        rvCoins.addSimpleDivider()
        rvCoins.adapter = adapter.withFooter()
        initToolbar(R.string.mine_coins)
        setHasOptionsMenu(true)
        mViewMode.getCoinInfo(viewLifecycleOwner)

    }

    override fun FragmentMyCoinsBinding.initListener() {
        mViewMode.setLayoutStateFlow(adapter.loadStateFlow)
        mViewMode.coinHistoryListLiveData.collectListWhenResumed(viewLifecycleOwner) {
            adapter.submitData(it)
        }
        mViewMode.rankingClickLiveData.observe(viewLifecycleOwner){
            findNavController().navigate(R.id.action_myCoins_to_coinRanking)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        menu.add(0, R.string.coin_ranking, 0, R.string.coin_ranking)
            .setIcon(R.drawable.ic_ranking)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.string.coin_ranking){
            mViewMode.onRakingClick()
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onRefresh() {
        adapter.refresh()
        mViewMode.getCoinInfo(viewLifecycleOwner)
    }

    override fun onRetry(view: View) {
        adapter.refresh()
        mViewMode.getCoinInfo(viewLifecycleOwner)
    }

    override fun initData() {
        super.initData()
    }
}